﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32;

namespace PocketDictionaryMerge
{
    public partial class Form1 : Form
    {
        private const string pcmDeviceLocation = @"\Program Files\PCMKeyboard\pcmKeyboard.dll";
        private const string pcmStorageCardLocation = @"\Storage Card\Program Files\PCMKeyboard\pcmKeyboard.dll";
        private const string pcmDeviceFolder = @"\Program Files\PCMKeyboard\";
        private const string pcmStorageCardFolder = @"\Storage Card\Program Files\PCMKeyboard\";

        private string pocketCMFolder = string.Empty;

        private List<string> wordsToRemove = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(pcmDeviceLocation))
            {
                pocketCMFolder = pcmDeviceFolder;
            }
            else
            {
                pocketCMFolder = pcmStorageCardFolder;
            }            
//            this.WriteLine("PCM = " + pocketCMFolder);            
        }
        private void WriteLine(string message)
        {
            this.textBoxOutput.Text += message + Environment.NewLine;
            this.textBoxOutput.SelectionStart = this.textBoxOutput.Text.Length;
            this.textBoxOutput.ScrollToCaret();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            
        }

        private static List<string> ReadDictionary(string fileName)
        {
            StreamReader reader = new StreamReader(fileName);
            List<string> words = new List<string>();
            while (reader.Peek() > 0)
            {
                words.Add(reader.ReadLine());
            }

            var dictionaryFile =
                from line in words
                select line;

            List<string> result = new List<string>(dictionaryFile.ToList().Distinct<string>());

            return result;
        }

        private void menuItemMerge_Click(object sender, EventArgs e)
        {
            Merge();
        }

        private void Merge()
        {
            try
            {
                RegistryKey keyboardKey = Registry.CurrentUser.OpenSubKey(@"Software\PocketCM\Keyboard");
                string keyboardDictionary = keyboardKey.GetValue("Dictionary") as string;
                string keyboardDictionaryName = string.Empty;
                string customWords = string.Empty;
                if ( (!string.IsNullOrEmpty(keyboardDictionary)) || (this.wordsToRemove.Count > 0) )
                {
                    keyboardDictionaryName = keyboardDictionary + ".dict";
                    keyboardDictionary = pocketCMFolder + keyboardDictionary + ".dict";
                    customWords = pocketCMFolder + "word.txt";
                    this.WriteLine("Using dict - " + keyboardDictionary);

                    // Read and append words
                    var mainDictionary = ReadDictionary(keyboardDictionary);
                    this.WriteLine("Read " + mainDictionary.Count + " words from dictionary.");

                    var newWords = new List<string>();
                    if (File.Exists(customWords))
                        newWords = ReadDictionary(customWords);

                    this.WriteLine("Read " + newWords.Count + " new words.");

                    if (newWords.Count == 0 & this.wordsToRemove.Count == 0)
                    {
                        this.WriteLine("Nothing to do.");
                    }

                    foreach (string word in newWords)
                    {
                        if (!mainDictionary.Contains<string>(word))
                        {
                            mainDictionary.Add(word);
                            this.WriteLine("Added " + word);
                        }
                    }
                    this.WriteLine("Added " + newWords.Count + " words.");

                    // Sort
                    this.WriteLine("Sorting.");
                    mainDictionary.Sort();

                    if (this.wordsToRemove.Count > 0)
                    {
                        foreach (string word in this.wordsToRemove)
                        {
                            int removedCount = mainDictionary.RemoveAll(delegate(string s)
                            {
                                if (s.Equals(word, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    return true;                                    
                                }
                                else
                                    return false;
                            } );
                            if (removedCount > 0)
                                this.WriteLine("Removed " + word);
                        }
                    }


                    // Backup
                    File.Delete(keyboardDictionary + ".old");
                    File.Move(keyboardDictionary, keyboardDictionary + ".old"); // rename input file
                    this.WriteLine("Backed up old dictionary.");

                    this.WriteLine("Writing new dictionary.");
                    TextWriter writer = File.CreateText(keyboardDictionary);
                    foreach (string word in mainDictionary)
                    {
                        writer.WriteLine(word);
                    }
                    writer.Flush();
                    writer.Close();
                    writer.Dispose();
                    // Empty word.txt file
                    File.CreateText(customWords);
                    this.WriteLine("New dictionary written ok.");

                    File.Delete(keyboardDictionary + ".old");
                    File.Delete(@"\Storage Card\" + keyboardDictionaryName);
                    File.Copy(keyboardDictionary, @"\Storage Card\" + keyboardDictionaryName);
                    this.WriteLine("Backed up new dictionary to" + @"\Storage Card\" + keyboardDictionaryName);
                }
                else
                {
                    this.WriteLine("Nothing to do.");
                }
            }
            catch (Exception ex)
            {
                this.WriteLine(ex.ToString());
            }
            finally
            {
                this.WriteLine("Done.");
            }
        }

        private void menuItemRemove_Click(object sender, EventArgs e)
        {
            Remove removeForm = new Remove();
            this.wordsToRemove = new List<string>();
            if (removeForm.ShowDialog() == DialogResult.OK)
            {
                this.wordsToRemove = removeForm.WordsToRemove.Split(',').ToList<string>();
            }
            Merge();
        }
    }
}